<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Area extends Model
{
    //
    protected $fillable = ['name', 'level', 'parent_id'];

    /**
     * 获取所有权限树
     * @param array|null $types
     * @return array
     */
    public static function getTreeInfo()
    {

        $sourceArray = static::get()->toArray();

        $targetArray = static::getTree($sourceArray, 0);

        return $targetArray;
    }

    /**
     * 根据数据获取权限树
     * @param $sourceArray
     * @param int $pid
     * @return array
     */
    public static function getTree($sourceArray, $pid = 0)
    {
        $targetArray = [];
        foreach ($sourceArray as $v) {
            if ($v['parent_id'] == $pid) {
                $area = static::getTree($sourceArray, $v['id']);
                if (!empty($area)) {
                    $v['area'] = $area;
                    $targetArray[] = $v;
                } else {
                    $targetArray[] = $v;
                }
            }
        }

        return $targetArray;
    }
}
